<!--

/*
** Copyright (c) 2016 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/

-->

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebGL BlitFramebuffer Tests</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<script src="../../js/js-test-pre.js"></script>
<script src="../../js/webgl-test-utils.js"></script>
<script src="../../js/glsl-conformance-test.js"></script>
</head>
<body>
<canvas id="example" width="8" height="8"></canvas>
<div id="description"></div>
<div id="console"></div>

<script>
"use strict";

var wtu = WebGLTestUtils;
description("This test verifies the functionality of blitFramebuffer.");

var gl = wtu.create3DContext("example", undefined, 2);

function checkPixel(color, expectedColor) {
  var tolerance = 3;
  return (Math.abs(color[0] - expectedColor[0]) <= tolerance &&
          Math.abs(color[1] - expectedColor[1]) <= tolerance &&
          Math.abs(color[2] - expectedColor[2]) <= tolerance &&
          Math.abs(color[3] - expectedColor[3]) <= tolerance);
}

function blitframebuffer_outside_readbuffer(readbufferFormat, drawbufferFormat) {
    debug("");
    debug("blitting outside of read framebuffer, read buffer format is: " + wtu.glEnumToString(gl, readbufferFormat) + ", draw buffer format is: " + wtu.glEnumToString(gl, drawbufferFormat));

    // Initiate data to read framebuffer
    var size_read = 3;
    var uint_read = new Uint8Array(size_read * size_read * 4);
    var start = 0x20;
    for (var ii = 0; ii < size_read * size_read * 4; ii += 4) {
        for (var jj = 0; jj < 3; ++jj) {
          uint_read[ii + jj] = start;
        }
        uint_read[ii + 3] = 0xff;
        start += 0x10;
    }

    // Create read framebuffer and feed data to read buffer
    // Read buffer may has srgb image
    var tex_read = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex_read);
    gl.texImage2D(gl.TEXTURE_2D, 0, readbufferFormat, size_read, size_read, 0, gl.RGBA, gl.UNSIGNED_BYTE, uint_read);

    var fbo_read = gl.createFramebuffer();
    gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_read);
    gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex_read, 0);

    // Initiate data to draw framebuffer
    var size_draw = 7;
    var uint_draw = new Uint8Array(size_draw * size_draw * 4);
    for (var ii = 0; ii < size_draw * size_draw * 4; ii += 4) {
        for (var jj = 0; jj < 3; ++jj) {
            uint_draw[ii + jj] = 0x10;
        }
        uint_draw[ii + 3] = 0xff;
    }

    // Create draw framebuffer and feed data to draw buffer
    // Draw buffer may has srgb image
    var tex_draw = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex_draw);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

    gl.texImage2D(gl.TEXTURE_2D, 0, drawbufferFormat, size_draw, size_draw, 0, gl.RGBA, gl.UNSIGNED_BYTE, uint_draw);

    var fbo_draw = gl.createFramebuffer();
    gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fbo_draw);
    gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex_draw, 0);

    if (gl.checkFramebufferStatus(gl.READ_FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE) {
        var ref = [
            // The reference pixels of the 1st line: (0, 0) ~ (6, 0)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],

            // The reference pixels of the 2nd line: (0, 1) ~ (6, 1)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],

            // The reference pixels of the 3rd line: (0, 2) ~ (6, 2)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x20, 0x20, 0x20, 0xff], [0x30, 0x30, 0x30, 0xff],
            [0x40, 0x40, 0x40, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],

            // The reference pixels of the 4th line: (0, 3) ~ (6, 3)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x50, 0x50, 0x50, 0xff], [0x60, 0x60, 0x60, 0xff],
            [0x70, 0x70, 0x70, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],

            // The reference pixels of the 5th line: (0, 4) ~ (6, 4)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x80, 0x80, 0x80, 0xff], [0x90, 0x90, 0x90, 0xff],
            [0xa0, 0xa0, 0xa0, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],

            // The reference pixels of the 6th line: (0, 5) ~ (6, 5)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],

            // The reference pixels of the 7th line: (0, 6) ~ (6, 6)
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],
            [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff], [0x10, 0x10, 0x10, 0xff],
        ];

        // The 1st round test: blit read framebuffer to the image in draw framebuffer
        // All directions of the read region have pixels outside of the read buffer
        // The src region and/or dst region may be reversed during blitting.
        var test1 = [
             [-1, 4, 1, 6], // reverse neither src nor dst
             [4, -1, 1, 6], // reverse src only
             [-1, 4, 6, 1], // reverse dst only
             [4, -1, 6, 1]  // reverse both src and dst
        ];

        var readbufferHasSRGBImage = (readbufferFormat == gl.SRGB8_ALPHA8);
        var drawbufferHasSRGBImage = (drawbufferFormat == gl.SRGB8_ALPHA8);

        for (var i = 0; i < 4; ++i) {
            debug("");
            switch (i) {
                case 0: debug("reverse neither src region nor dst region"); break;
                case 1: debug("reverse src region only"); break;
                case 2: debug("reverse dst region only"); break;
                case 3: debug("reverse both src region and dst region"); break;
            }
            var srcStart = test1[i][0];
            var srcEnd = test1[i][1];
            var dstStart = test1[i][2];
            var dstEnd = test1[i][3];
            var realBlittedDstStart = 2;
            var realBlittedDstEnd = 5;
            gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_read);
            gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fbo_draw);
            gl.blitFramebuffer(srcStart, srcStart, srcEnd, srcEnd, dstStart, dstStart, dstEnd, dstEnd, gl.COLOR_BUFFER_BIT, gl.LINEAR);

            // Read pixels and check the correctness.
            var pixels = new Uint8Array(size_draw * size_draw * 4);
            gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_draw);
            gl.readPixels(0, 0, size_draw, size_draw, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

            for (var ii = 0; ii < size_draw; ++ii) {
                for (var jj = 0; jj < size_draw; ++jj) {
                    var loc = ii * size_draw + jj;
                    var color = [pixels[loc * 4], pixels[loc * 4 + 1], pixels[loc * 4 + 2], pixels[loc * 4 + 3]];

                    // We may need to reverse the reference loc if necessary
                    var ref_loc = loc;
                    var reverse_src = (srcStart < srcEnd);
                    var reverse_dst = (dstStart < dstEnd);
                    var reversed = reverse_src ^ reverse_dst;
                    if (reversed) {
                        ref_loc = (size_draw - ii - 1) * size_draw + (size_draw - jj -1);
                    }
                    var expectedColor = ref[ref_loc];

                    // We may need to covert the color space for pixels in blit region
                    if ((readbufferHasSRGBImage ^ drawbufferHasSRGBImage) &&
                        (ii >= realBlittedDstStart && ii < realBlittedDstEnd && jj >= realBlittedDstStart && jj < realBlittedDstEnd)) {
                        if (drawbufferHasSRGBImage) {
                            expectedColor = wtu.linearToSRGB(expectedColor);
                        } else {
                            expectedColor = wtu.sRGBToLinear(expectedColor);
                        }
                    }
                    if (checkPixel(color, expectedColor) == true) {
                        testPassed("pixel at [" + jj + ", " + ii + "] is (" + color + "). It is correct!");
                    } else {
                        testFailed("pixel at [" + jj + ", " + ii + "] should be (" + expectedColor + "), but the actual color is (" + color + ")");
                    }
                }
            }
        }

        // The 2nd round test: blit read framebuffer to the image in draw framebuffer
        // Only one direction of the read region have pixels outside of the read buffer
        var tests = [
             [-1, 0], // pixels are outside the left edge of the read buffer
             [0, -1], // pixels are outside the bottom edge of the read buffer
             [1, 0],  // pixels are outside the right edge of the read buffer
             [0, 1]   // pixels are outside the top edge of the read buffer
        ];
        for (var i = 0; i < 4; ++i) {
            debug("");
            switch (i) {
                case 0: debug("verify that pixels lying outside the left edge of the read buffer should remain untouched"); break;
                case 1: debug("verify that pixels lying outside the bottom edge of the read buffer should remain untouched"); break;
                case 2: debug("verify that pixels lying outside the right edge of the read buffer should remain untouched"); break;
                case 3: debug("verify that pixels lying outside the top edge of the read buffer should remain untouched"); break;
            }
            gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_read);
            gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fbo_draw);
            var srcX = tests[i][0];
            var srcY = tests[i][1];
            var offset = dstStart - srcStart;
            gl.blitFramebuffer(srcX, srcY, srcX + size_read, srcY + size_read,
                               srcX + offset, srcY + offset, srcX + offset + size_read, srcY + offset + size_read,
                               gl.COLOR_BUFFER_BIT, gl.LINEAR);

            // Read pixels and check the correctness.
            var pixels = new Uint8Array(size_draw * size_draw * 4);
            gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_draw);
            gl.readPixels(0, 0, size_draw, size_draw, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
            for (var ii = srcY + offset; ii < srcY + offset + size_read; ++ii) {
                for (var jj = srcX + offset; jj < srcX + offset + size_read; ++jj) {
                    var loc = ii * size_draw + jj;
                    var color = [pixels[loc * 4], pixels[loc * 4 + 1], pixels[loc * 4 + 2], pixels[loc * 4 + 3]];
                    var expectedColor = ref[loc];
                    // We may need to covert the color space for pixels in blit region
                    if ((readbufferHasSRGBImage ^ drawbufferHasSRGBImage) &&
                        (ii >= realBlittedDstStart && ii < realBlittedDstEnd && jj >= realBlittedDstStart && jj < realBlittedDstEnd)) {
                        if (drawbufferHasSRGBImage) {
                            expectedColor = wtu.linearToSRGB(expectedColor);
                        } else {
                            expectedColor = wtu.sRGBToLinear(expectedColor);
                        }
                    }
                    if (checkPixel(color, expectedColor) == true) {
                        testPassed("pixel at [" + jj + ", " + ii + "] is (" + color + "). It is correct!");
                    } else {
                        testFailed("pixel at [" + jj + ", " + ii + "] should be (" + expectedColor + "), but the actual color is (" + color + ")");
                    }
                }
            }
        }
    } else {
        testFailed("framebuffer not complete");
    }

    gl.bindTexture(gl.TEXTURE_2D, null);
    gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
    gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
    gl.deleteFramebuffer(fbo_read);
    gl.deleteFramebuffer(fbo_draw);
    gl.deleteTexture(tex_read);
    gl.deleteTexture(tex_draw);
};

if (!gl) {
    testFailed("WebGL context does not exist");
} else {
    testPassed("WebGL context exists");
    blitframebuffer_outside_readbuffer(gl.RGBA8, gl.RGBA8);
    blitframebuffer_outside_readbuffer(gl.RGBA8, gl.SRGB8_ALPHA8);
    blitframebuffer_outside_readbuffer(gl.SRGB8_ALPHA8, gl.RGBA8);
    blitframebuffer_outside_readbuffer(gl.SRGB8_ALPHA8, gl.SRGB8_ALPHA8);
}

var successfullyParsed = true;
</script>
<script src="../../js/js-test-post.js"></script>

</body>
</html>
